package db

import (
	"fmt"
	"log"
	"time"
)

var LogActionType struct {
	Add    string
	Delete string
	Update string
}

func init() {

	LogActionType.Add = "add"
	LogActionType.Delete = "delete"
	LogActionType.Update = "update"
}

// 查询日志

/*
startTime
endTime
actionType   操作类型
module  操作模块
platForm  平台
userId 用户id
*/
func (this *ServerLog) QueryLog(startTime, endTime, actionType, module, platForm, userId string) (as []*ServerLog, err error) {

	sqlStr := fmt.Sprintf("createTime >= '%s' and createTime <= '%s' ", startTime, endTime)

	log.Println("QueryLog params:", startTime, endTime, actionType, module, platForm, userId)

	if actionType != "" {
		sqlStr += fmt.Sprintf("  and actionType = '%s' ", actionType)
	}

	if module != "" {
		sqlStr += "  and module like ('%" + module + "%') "
	}

	if platForm != "" {
		sqlStr += fmt.Sprintf("  and platform = '%s' ", platForm)
	}

	if userId != "" {
		sqlStr += fmt.Sprintf("  and userId = '%s' ", userId)
	}

	sqlStr = "select id, date, userName, userId, module, actionType, platform, createTime from  execlog  where " + sqlStr + " ; "

	log.Println("QueryLog sqlStr:", sqlStr)

	rows, err := db.Query(sqlStr)
	if err != nil {
		return
	}

	defer rows.Close()

	for rows.Next() {

		serverLog := new(ServerLog)
		err = rows.Scan(&serverLog.Id, &serverLog.Date, &serverLog.UserName, &serverLog.UserId, &serverLog.Module, &serverLog.ActionType, &serverLog.Platform, &serverLog.CreateTime)

		if err != nil {
			return
		}

		as = append(as, serverLog)
	}

	return
}

// 查询日志详情
func (this *ServerLog) QueryLogDetail(logId int) (a ServerLog, err error) {
	err = db.QueryRow("select id, date, userName, userId, module,oldContent,newContent, actionType, platform, createTime from  execlog  where id = ?", logId).Scan(
		&a.Id, &a.Date, &a.UserName, &a.UserId, &a.Module, &a.OldContent, &a.NewContent, &a.ActionType, &a.Platform, &a.CreateTime)
	if err != nil {
		return
	}
	return
}

// 删除日志
func (this *ServerLog) DeleteLog() {

}

// 记录操作日志
func (this *ServerLog) RecordLog() {
	this.Date = time.Now().Local().Format("2006-01-02")
	_, err := db.Exec("insert into execlog (date, userName, userId, `actionType`, `module`, oldContent, newContent, platform) values (?, ?, ?, ?, ?, ?, ?, ?)",
		this.Date, this.UserName, this.UserId, this.ActionType, this.Module, this.OldContent, this.NewContent, this.Platform)
	if err != nil {
		log.Println("日志记录失败,err=", err)
		return
	}
}
